//
//  HykOauthViewController.swift
//  sinaWeiBo
//
//  Created by hyk on 15/11/26.
//  Copyright © 2015年 hyk. All rights reserved.
//

import UIKit

//MARK ：- 类似于MB 框架
import SVProgressHUD

class HykOauthViewController: UIViewController {

    override func loadView() {
        //因为是界面大小，所以不用设置约束
        view = webView
        
        //设置代理
        webView.delegate = self
    }
    
    ///加载授权的界面
    override func viewDidLoad() {
        super.viewDidLoad()
       
        //加载授权界面
        let request = NSURLRequest(URL: HykNetworkTool.shardInstance.oauthURL())

        webView.loadRequest(request)
        
        //设置登录授权界面的导航栏
        //左边
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFill")
        
        //右边
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
    }
    
//    document.getElementById('userId').value='18317957953@163.com'
//    document.getElementById('passwd').value='lovejuan1201'
    ///填充账号
    func autoFill(){
      let js = "document.getElementById('userId').value='18317957953';document.getElementById('passwd').value='lovejuan1201';"
        //webview执行js代码
        webView.stringByEvaluatingJavaScriptFromString(js)
        
    
    }
    // 调用单例时加载access token
    func loadAccessToken(code:String){
        // 发送网络请求
        HykNetworkTool.shardInstance.loadAccessToken(code){(result,error) ->() in
            
            //判断当授权失败时
            if error != nil || result == nil {
    //   告诉用户出错了
    SVProgressHUD.showErrorWithStatus("你的网络不给力...", maskType: SVProgressHUDMaskType.Black)

                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                    
                    self.close()
                })
                
                return
            }
            //查看打印的结果
//            print(result)
            
            //字典转模型
            let userAccount = HykUserAccount(dict: result!)
            
            //保存对象
           userAccount.saveUserAccount()
            print("userAccount:\(userAccount)")
            
            //切换界面
            AppDelegate.switchRootViewController(false)
        }
    
    }
        
    ///关闭控制器
    func close(){
        
        //关闭SVP
        SVProgressHUD.dismiss()
      dismissViewControllerAnimated(true, completion: nil)
        
    }

    //MARK : 懒加载
    
    /// webView
    private lazy var webView = UIWebView()
}

//MARK : - 扩展CZOauthViewController 实现 UIWebViewDelegate 协议

extension HykOauthViewController: UIWebViewDelegate{
   //webView开始加载链接
    func webViewDidStartLoad(webView: UIWebView) {
        //showWithStatus一直显示，不会主动关闭
        //showInfoWithStatus 过段时间会消失
        SVProgressHUD.showWithStatus("正在玩命加载中...", maskType: SVProgressHUDMaskType.Gradient)
    }
   //webView结束加载
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    //监听webView点击的加载链接，每当webview加载一个链接就会通过这个dialing方法来询问我们这个地址是否可以加载  ，true表示可以加载，false表示不加载
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let uslString = request.URL!.absoluteString
//        print("urlString:\(uslString)")
        //点击取消 https://m.baidu.com/?error_uri=%2Foauth2%2Fauthorize&error=access_denied&error_description=user%20denied%20your%20request.&error_code=21330&from=844b&vit=fps
        //点击授权 http://www.baidu.com/?code=0a2752c212540c3b0747edf836889a31
        
        //根据截取点击取消和授权按钮不同的字符串来判断两者的点击事件
        
        /*----接下来的思路-------------------
        1. 如果加载的不是授权回调页面,直接加载网页,
        2. 如果加载的是授权回调页面,对后面的参数进行判断,如果有code=表示点击了授权按钮,否则点击取消
        */
        
        // 判断是否是回调地址 ，不是以回调地址开头的就直接加载网页
        if !uslString.hasPrefix(HykNetworkTool.shardInstance.redirect_uri){
            
          return true
        }
        
        //可选绑定 ， 判断后面是否跟有参数
        if let query = request.URL?.query {
//            print("query:\(query)")
            //判断是否是以“code=”开头
             let codeString = "code="
            if query.hasPrefix(codeString) {
               //点击授权,截取code的值
                let nsQuery = query as NSString
                //截取“code=”五个字符之后的字符
                let code = nsQuery.substringFromIndex(codeString.characters.count)
//                print("code:\(code)")
                
                //调用加载access token的方法
                loadAccessToken(code)
                
            }else{
               //点击取消
                print("点击取消")
                self.close()
            
            }
            
        }
        // 不去加载授权回调地址
        return true
    }

}

